package org.ysh.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.http.HttpStatus;
import org.ysh.core.cache.Constants;
import org.ysh.core.utils.ServletUtils;
import org.ysh.core.utils.SqlUtil;
import org.ysh.core.web.PageDomain;
import org.ysh.core.web.TableDataInfo;
import org.ysh.core.web.TableSupport;
import org.ysh.domain.User;

import java.util.List;

public abstract class BaseController {

    /**
     * 获取当前用户
     * @return
     */
    protected User getCurrentUser() {
        return (User)ServletUtils.getRequest().getSession().getAttribute(Constants.CURRENT_USER);
    }

    protected String getCurrentFondsCode() {
        return (String)ServletUtils.getRequest().getSession().getAttribute(Constants.CURRENT_FONDS);
    }

    /**
     * 开启分页
     */
    protected void startPage(){
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
        Boolean reasonable = pageDomain.getReasonable();
        PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
    }

    /**
     * 清除分页
     */
    protected void clearPage(){
        PageHelper.clearPage();
    }


    protected TableDataInfo getDataTable(List<?> list)
    {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setData(list);
        rspData.setMsg("查询成功");
        rspData.setCount(new PageInfo(list).getTotal());
        return rspData;
    }

    protected TableDataInfo getDataTable(Page<?> page)
    {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setData(page.getResult());
        rspData.setMsg("查询成功");
        rspData.setCount(page.getTotal());
        return rspData;
    }
}
